package com.junko.api.resolver;

import com.alibaba.fastjson.JSONObject;
import com.junko.core.exception.BusinessException;
import com.junko.core.exception.LockedException;
import com.junko.core.exception.NoLoginException;
import com.junko.core.exception.NoPermissionException;
import com.junko.core.tool.ToolWeb;
import com.junko.model.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 全局异常处理
 */
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    private Logger logger = LogManager.getLogger(GlobalExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //不是逻辑错误
        if (!(ex instanceof BusinessException)) {
            ex.printStackTrace();
        }
        //不是异步的，且不是异步文件上传、文件下载异常
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        JsonResult jsonResult = JsonResult.fail(ex.getMessage());
        if (ex instanceof NoLoginException) {
            jsonResult = JsonResult.fail(-44, "请先登陆再操作", ToolWeb.getReferer(request));
        } else if (ex instanceof LockedException) {
            jsonResult = JsonResult.fail(-55, "您的账号已被禁用");
        } else if (ex instanceof NoPermissionException) {
            jsonResult = JsonResult.fail(-66, "您没有该执行权限");
        } else if (ex instanceof BusinessException) {
            jsonResult = JsonResult.fail(StringUtils.isEmpty(ex.getMessage()) ? "出错了" : ex.getMessage());
        }
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(JSONObject.toJSONString(jsonResult));
        } catch (IOException e) {
            logger.error("返回错误信息异常:" + e.getMessage(), e);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
        return new ModelAndView();//return null会出现 getWriter() has already been called for this response 的异常
    }
}
